import EvaluationRecord from '@/components/EvaluationRecord';
import GuidanceRecord from '@/components/GuidanceRecord';
import HealthRecords from '@/components/HealthRecords';
import PhysiologicalMonitoring from '@/components/PhysiologicalMonitoring';
import TrainingRecord from '@/components/TrainingRecord';
import {
  patient_callLog_list,
  patient_guidance_info,
  submit_patient_guidance,
} from '@/services/guide';
import { get_patient_info } from '@/services/patient';
import age from '@/utils/age';
import timeToHms from '@/utils/time';
import {
  ActionType,
  ProColumns,
  ProDescriptions,
  ProForm,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Card, DatePicker, Divider, Form, Input, message, Modal, Switch, Tabs } from 'antd';
import dayjs from 'dayjs';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';
const { TextArea } = Input;

interface Iprops {
  isShowInHospitalModal: (status: boolean) => void;
  inHospitalModal: boolean;
  guideId: number | undefined;
  patientId: number | undefined;
  actionRef: React.MutableRefObject<ActionType | undefined>;
}
type GithubIssueItem = {
  id: number;
  time: string;
  call_type: number;
  create_time: string;
  status: number;
  status_d: string;
};
type Info = {
  family_address: string;
  area_name: string;
  city_name: string;
  province_name: string;
  birth: string;
  id: number;
  phone: string;
  name: string;
  sex: number;
  id_card: string;
  address: string;
  info: any;
};
// 指导内容
var chat_content = '';
// 下次指导时间
var chat_time = moment(moment().day(moment().day() + 7)).format('YYYY-MM-DD');
// 下次指导备注
var remark = '';
const InHospitalGuide = (props: Iprops) => {
  const actionRef = useRef<ActionType>();
  const { isShowInHospitalModal, inHospitalModal, guideId, patientId } = props;
  // 控制指导计划的显示与隐藏
  const [isShowPlan, setIsShowPlan] = useState(false);
  // 是否有有效的通话记录
  const [saveflag, setsaveflag] = useState(false);
  // 存储患者信息
  const [patientinfo, setPatientInfo] = useState<any>(undefined);
  // 存储指导详情
  const [guideInfo, setGuideInfo] = useState<any>(undefined);

  useEffect(() => {
    //   页面初始化获取患者信息
    const getData = async () => {
      if (patientId) {
        let res: any = await get_patient_info({ id: patientId });
        console.log('患者详情', res);
        if (res.code === 200) {
          setPatientInfo(res.data);
        }
      }
    };
    // 获取指导详情信息
    const guideInfo = async () => {
      if (guideId) {
        let res: any = await patient_guidance_info({ id: guideId });
        console.log('指导详情', res);
        if (res.code == 200) {
          setGuideInfo(res.data);
        }
      }
    };
    getData();
    guideInfo();
  }, []);

  //获取呼叫记录
  const get_patient_callLog_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    let request_body = {
      ...params,
      pcurrent: params.current,
      pageSize: params.pageSize,
      patient_guidance_id: guideId,
    };
    let res = await patient_callLog_list(request_body);
    console.log('呼叫记录', res);

    // 是否有有效通话记录
    setsaveflag(res.data.save_flag == 1);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };
  // 呼叫跳转  type video/audio 视频/语音
  const send_call = (type: string) => {
    console.log(type);
    if (guideId && patientId) {
      window.open(`/guide/my_guide/${type}?id=${guideId}&patient_id=${patientId}`);
    }
  };
  window.addEventListener('message', function (event: any) {
    // 在父窗口中显示子窗口发来的消息
    console.log('fff', event.data);
    if (event.data == 'refresh') {
      actionRef.current?.reload();
    }
  });
  window.addEventListener('message', function (event: any) {
    // 在父窗口中显示子窗口发来的消息
    console.log('fff', event.data);
    if (event.data == 'close') {
      isShowInHospitalModal(false);
    }
  });

  //修改指导记录
  const onChangecontent = (e: { target: { value: string } }) => {
    chat_content = e.target.value;
  };

  //修改下一次指导时间
  const onChangetime = (e: any) => {
    console.log('eee', e);
    if (e != null) {
      chat_time = moment(e).format('YYYY-MM-DD');
    } else {
      chat_time = e;
    }
    console.log('chat_time', chat_time);
  };

  // 修改备注
  const onChangeRemark = (e: { target: { value: string } }) => {
    remark = e.target.value;
  };

  // 结束指导
  const end_guide = async () => {
    console.log('plan_time', chat_time);
    if (chat_content.replace(/^\s\s*/, '').replace(/\s\s*$/, '') == '') {
      message.warning('请填写指导记录');
      return;
    }
    let request_body;
    if (isShowPlan) {
      if (chat_time == null) {
        message.warning('请选择下次计划指导时间');
        return;
      } else {
        request_body = {
          id: guideId,
          content: chat_content,
          plan_time: chat_time,
          remark: remark ?? remark,
        };
      }
    } else {
      request_body = {
        id: guideId,
        content: chat_content,
      };
    }
    let res: any = await submit_patient_guidance(request_body);
    if (res.msg == 'ok') {
      message.success('指导已结束');
      isShowInHospitalModal(false);
    } else {
      message.error(res.msg);
    }
  };

  // 通话记录
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '通话时间',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '通话方式',
      dataIndex: 'call_type',
      align: 'center',
      valueEnum: {
        0: {
          text: '语音',
        },
        1: {
          text: '视频',
        },
      },
    },
    {
      title: '通话时长',
      dataIndex: 'time',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => {
        if (record.status != 3) {
          return record.status_d;
        } else {
          return timeToHms(record.time);
        }
      },
    },
  ];
  return (
    <Modal
      title="院内指导"
      open={inHospitalModal}
      onCancel={() => isShowInHospitalModal(false)}
      width={1500}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Button
          key="video"
          style={{ padding: '0 12px', margin: '0 20px 20px 0' }}
          type="primary"
          onClick={() => send_call('video')}
        >
          视频指导
        </Button>
        <Button
          key="audio"
          style={{ padding: '0 12px', margin: '0 20px 20px 0' }}
          type="primary"
          onClick={() => send_call('audio')}
        >
          语音指导
        </Button>
        <Button
          key="end"
          style={{ padding: '0 12px', margin: '0 20px 20px 0' }}
          onClick={() => end_guide()}
          type="primary"
        >
          结束指导
        </Button>
      </div>
      {patientinfo === undefined && guideInfo === undefined ? (
        ''
      ) : (
        <div style={{ display: 'flex' }}>
          <div style={{ flex: 3 }}>
            <Card>
              <ProDescriptions
                dataSource={guideInfo}
                columns={[
                  {
                    title: '手机号',
                    key: 'patient_phone',
                    dataIndex: 'patient_phone',
                  },
                  {
                    title: '姓名',
                    key: 'patient_name',
                    dataIndex: 'patient_name',
                  },
                  {
                    title: '性别',
                    key: 'patient_sex',
                    dataIndex: 'patient_sex',
                    valueType: 'select',
                    valueEnum: {
                      0: {
                        text: '未知',
                      },
                      1: {
                        text: '男',
                      },
                      2: {
                        text: '女',
                      },
                    },
                  },
                  {
                    title: '身份证号',
                    key: 'patient_idcard',
                    dataIndex: 'patient_idcard',
                  },
                  {
                    title: '年龄',
                    key: 'patient_birth',
                    dataIndex: 'patient_birth',
                    render: (_, record) => age(record.patient_birth),
                  },
                  {
                    title: '家庭地址',
                    key: 'patient_address',
                    dataIndex: 'patient_address',
                    render: (_, record) => {
                      return (
                        record.patient_province +
                        record.patient_ctiy +
                        record.patient_area +
                        record.patient_address
                      );
                    },
                  },
                  {
                    title: '备注',
                    key: 'remark',
                    dataIndex: 'remark',
                  },
                ]}
              ></ProDescriptions>
            </Card>
            <Tabs
              defaultActiveKey="通话记录"
              style={{ minHeight: '700px' }}
              items={[
                {
                  key: '通话记录',
                  label: '通话记录',
                  children: (
                    <ProTable<GithubIssueItem>
                      columns={columns}
                      actionRef={actionRef}
                      cardBordered
                      request={async (params = {}) => get_patient_callLog_list(params)}
                      editable={{
                        type: 'multiple',
                      }}
                      rowKey={(record) => record.id}
                      search={false}
                      options={false}
                      pagination={{
                        pageSize: 10,
                      }}
                      dateFormatter="string"
                      headerTitle=""
                    />
                  ),
                },
                {
                  key: '生理监测',
                  label: '生理监测',
                  children: (
                    <PhysiologicalMonitoring patientId={patientId}></PhysiologicalMonitoring>
                  ),
                },
                {
                  key: '评估记录',
                  label: '评估记录',
                  children: (
                    <EvaluationRecord type={false} patientId={patientId}></EvaluationRecord>
                  ),
                },
                {
                  key: '训练记录',
                  label: '训练记录',
                  children: <TrainingRecord patientId={patientId}></TrainingRecord>,
                },
                {
                  key: '指导记录',
                  label: '指导记录',
                  children: <GuidanceRecord patientId={patientId}></GuidanceRecord>,
                },
                {
                  key: '健康档案',
                  label: '健康档案',
                  children: <HealthRecords info={patientinfo?.info}></HealthRecords>,
                },
              ]}
            // onChange={onChange}
            />
          </div>
          <div
            style={{
              marginLeft: '20px',
              flex: 1,
              border: '1px solid #eee',
              display: 'flex',
              flexDirection: 'column',
              minHeight: '500px',
            }}
          >
            <div>
              <div style={{ margin: ' 0 10px 0 10px' }}>
                <ProForm
                  layout="horizontal"
                  labelCol={{ span: 9 }}
                  wrapperCol={{ span: 15 }}
                  submitter={{
                    searchConfig: {
                      submitText: '提交',
                      resetText: '重置',
                    },
                    resetButtonProps: {
                      style: {
                        // 隐藏重置按钮
                        display: 'none',
                        position: 'absolute',
                        left: 'calc(50% - 107px)',
                      },
                    },
                    submitButtonProps: {
                      style: {
                        display: 'none',
                        position: 'absolute',
                        right: 'calc(50% - 107px)',
                      },
                    },
                  }}
                >
                  <Form.Item name="status" label="下次指导计划">
                    <Switch
                      checkedChildren="开启"
                      unCheckedChildren="关闭"
                      defaultChecked={false}
                      onChange={(checked: boolean) => setIsShowPlan(checked)}
                    />
                  </Form.Item>
                  {isShowPlan ? (
                    <>
                      <Form.Item
                        name="time"
                        label="指导时间"
                        rules={[
                          {
                            required: true,
                            message: '请选择指导时间',
                          },
                        ]}
                      >
                        <DatePicker
                          name="time"
                          onChange={onChangetime}
                          defaultValue={moment(moment().day(moment().day() + 7), 'YYYY-MM-DD')}
                          disabledDate={(current) =>
                            (current && current < dayjs().endOf('day')) ||
                            current > moment().add(7, 'days')
                          }
                        />
                      </Form.Item>
                      <Form.Item
                        name="text"
                        label="备注"
                        rules={[
                          {
                            max: 100,
                            message: '最多输入100个字符',
                          },
                        ]}
                      >
                        <TextArea
                          onChange={onChangeRemark}
                          name="text"
                          placeholder="请填写备注,最多100个字符"
                          rows={4}
                        />
                      </Form.Item>
                    </>
                  ) : (
                    ''
                  )}
                </ProForm>
              </div>
              <div style={{ margin: ' 0 10px 10px 10px' }}>
                <TextArea
                  name="text"
                  onChange={onChangecontent}
                  rows={10}
                  placeholder="请输入指导内容/记录/指导意见"
                  allowClear={true}
                  maxLength={100}
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </Modal>
  );
};
export default InHospitalGuide;
